package org.youyun56.gpsserver.plugins;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.Map.Entry;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.youyun56.gpsserver.CacheFactory;
import org.youyun56.gpsserver.command.CommandFactory;
import org.youyun56.gpsserver.common.DateUtils;
import org.youyun56.gpsserver.common.PathConfig;
import org.youyun56.gpsserver.common.SessionManager;
import org.youyun56.gpsserver.entity.Good;
import org.youyun56.gpsserver.net.GpsServer;

import com.j3.sql.GridUtils;

public class WangLangGood implements Runnable {
    public Hashtable<Integer, String> citys = new Hashtable<Integer, String>();
    private final static Logger log = Logger.getLogger(WangLangGood.class);
    private Integer id;
    private File goodIndex = new File(PathConfig.ROOT + File.separator + "wanglang.properties");
    private List<Good> goods = new ArrayList<Good>();
    private Properties props = new Properties();

    @Override
    public void run() {
        try {
            if (citys.isEmpty()) {
                initCitys();
            }
            getStartGoodId();
            catchGoods();
            parseGoods();
            saveGoods();
            writeStartGoodId();
            reset();
        }
        catch (Exception e) {
            log.error(e.getMessage(), e);
        }

    }

    private void reset() {
        goods.clear();
        props.clear();
    }

    private void saveGoods() {
        for (Good good : goods) {
            CacheFactory.instance.addGoodCache(good.getTargetCity(), good);
            SessionManager.brocast(good.getTargetCity(), CommandFactory.sendGood(CommandFactory.goodJson(good)).toString());
        }
    }

    private void parseGoods() {
        List<Good> result = new ArrayList<Good>();
        for (Good good : goods) {
            String[] str = good.getTxt().split("-->");
            if (str.length >= 2) {
                for (Entry<Integer, String> entry : citys.entrySet()) {
                    if (str[0].contains(entry.getValue())) {
                        good.setFromCity(entry.getKey());
                    }
                    if (str[1].contains(entry.getValue())) {
                        good.setToCity(entry.getKey());
                    }
                    if (good.getFromCity() != null && good.getToCity() != null)
                        break;
                }
                if (good.getFromCity() == null) {
                    good.setFromCity(-1);
                    log.error(String.format("From City parse Failure:  %s", good.getTxt()));
                }
                if (good.getToCity() == null) {
                    good.setToCity(-1);
                    log.error(String.format("To City parse Failure:  %s", good.getTxt()));
                }
                result.add(good);
            } else {
                log.error(String.format("parse Good failure: %s", good.getTxt()));
            }
        }
        goods = result;

    }

    private List<Good> catchGoods() throws SQLException {
        GridUtils grid = new GridUtils();
        String db = GpsServer.props.getProperty("wanglangdb", "1683333");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DAY_OF_YEAR, -1);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        c.set(Calendar.HOUR_OF_DAY, 18);
        grid.init(String
                .format("select id,content,addtime,user_xm,user_tel,user_mobi from `%s`.hyxx h INNER JOIN `%s`.`user` u on h.user_id = u.user_id  where id > %d and addtime > '%s' order by id asc",
                        db, db, id, DateUtils.formatFull(c.getTime())));
        while (grid.next()) {
            Good good = new Good();
            good.setTargetCity(124);
            good.setTxt(grid.get("content"));
            good.setAddTime(new Date(grid.getTimestamp("addtime").getTime()));
            StringBuilder sb = new StringBuilder("联系：").append(grid.get("user_xm") != null ? grid.get("user_xm") : "").append(", ")
                    .append(grid.get("user_tel") != null ? grid.get("user_tel") : "").append(", ")
                    .append(grid.get("user_mobi") != null ? grid.get("user_mobi") : "");
            good.setContact(sb.toString());
            goods.add(good);
            if (grid.getInt("id") > id) {
                id = grid.getInt("id");
            }
        }
        return goods;
    }

    private void writeStartGoodId() throws FileNotFoundException, IOException {
        props.setProperty("index", String.valueOf(id));
        props.store(new FileOutputStream(goodIndex), "");
    }

    private void getStartGoodId() throws FileNotFoundException, IOException {
        props.load(new FileInputStream(goodIndex));
        id = Integer.valueOf(props.getProperty("index", "-1"));
    }

    private void initCitys() throws SQLException {
        citys.clear();
        GridUtils grid = new GridUtils();
        grid.init("select id,replace(name,'市','') as name from city");
        while (grid.next()) {
            citys.put(grid.getInt("id"), grid.get("name"));
        }
    }
}
